package org.totoro.dead.listener;

import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.AcknowledgeMode;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.amqp.rabbit.listener.api.ChannelAwareMessageListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.totoro.dead.DealQueueProducer;

/**
 * @author YHL
 * @version V1.0
 * @Description:
 * @date 2018-02-02
 */
@Configuration
public class DeadQueueListener {


    @Autowired
    private ConnectionFactory connectionFactory;


    /**
     * 手动 ack，确认消息
     *
     * @return
     */
    @Bean
    public SimpleMessageListenerContainer loginFactory() {

        SimpleMessageListenerContainer simpleMessageListenerContainer = new SimpleMessageListenerContainer(connectionFactory);
        // 队列名称
        simpleMessageListenerContainer.setQueueNames(DealQueueProducer.queueNormalName);
        // 是否暴露注册通道
        simpleMessageListenerContainer.setExposeListenerChannel(true);
        // 设置ack 模式  为手动确认
        simpleMessageListenerContainer.setAcknowledgeMode(AcknowledgeMode.MANUAL);
        // 设置监听器
        simpleMessageListenerContainer.setMessageListener(new ChannelAwareMessageListener() {

            @Override
            public void onMessage(Message message, Channel channel) throws Exception {

                long deliveryTag = message.getMessageProperties().getDeliveryTag();

                channel.basicNack(deliveryTag, false, false);
            }
        });

        return simpleMessageListenerContainer;
    }


}
